package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.domain.BluePlateTags;
import com.smart.village.big.screen.mapper.ACTMapper;
import com.smart.village.big.screen.mapper.BluePlateStudyRoutesMapper;
import com.smart.village.big.screen.service.ACTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ACTServiceImpl implements ACTService {
    @Autowired
    private ACTMapper actMapper;
    @Autowired
    private BluePlateStudyRoutesMapper bluePlateStudyRoutesMapper;

    @Override
    public JSONObject getHomestayIntroduction(String townNumber, String villageNumber, int pageNum, int pageSize) {
        JSONObject homestayIntroduction = actMapper.getHomestayIntroduction1(townNumber, villageNumber);
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = actMapper.getHomestayIntroduction2(townNumber, villageNumber);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("rank", i + 1);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        homestayIntroduction.put("list", pageInfo.getList());
        homestayIntroduction.put("total", pageInfo.getTotal());
        return homestayIntroduction;
    }

    @Override
    public JSONObject getHomestayIntroductionCoordsList(String townNumber, String villageNumber, String merchantCategorySerialNumber) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        JSONObject crs = new JSONObject();
        crs.put("type", "name");
        JSONObject crsP = new JSONObject();
        crsP.put("name", "EPSG:4490");
        crs.put("properties", crsP);

        jsonObject.put("crs", crs);
        List<JSONObject> list = actMapper.getHomestayIntroductionCoordsList(townNumber, villageNumber, merchantCategorySerialNumber);
        List<JSONObject> features = Lists.newArrayList();
        list.forEach(coords -> {
            JSONObject feature = new JSONObject();
            feature.put("type", "Feature");
            feature.put("id", coords.getString("Shop_SerialNumber"));
            JSONObject geometry = new JSONObject();
            geometry.put("type", "point");
            geometry.put("coordinates", coords.getString("Coord").replace(" ", ""));
            feature.put("geometry", geometry);
            feature.put("properties", coords);
            if (!ObjectUtils.isEmpty(coords.getString("Coord")) && !coords.getString("Coord").replace(" ", "").equals("[]]")) {
                coords.remove("coords");
                features.add(feature);
            }
        });
        jsonObject.put("features", features);
        return jsonObject;
    }

    @Override
    public List<BluePlateTags> getAllBluePlateTags(String tagSerialNumber) {
        return actMapper.getAllBluePlateTags(tagSerialNumber);
    }

    @Override
    public JSONObject getServiceResourcesCoordsList(String townNumber, String villageNumber, String tagSerialNumber) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        JSONObject crs = new JSONObject();
        crs.put("type", "name");
        JSONObject crsP = new JSONObject();
        crsP.put("name", "EPSG:4490");
        crs.put("properties", crsP);

        jsonObject.put("crs", crs);
        List<JSONObject> list = actMapper.getServiceResourcesCoordsList(townNumber, villageNumber, tagSerialNumber);
        List<JSONObject> features = Lists.newArrayList();
        for (JSONObject coords : list) {
            JSONObject feature = new JSONObject();
            feature.put("type", "Feature");
            feature.put("id", coords.getString("Shop_SerialNumber"));
            JSONObject geometry = new JSONObject();
            geometry.put("type", "point");
            geometry.put("coordinates", coords.getString("Coord").replace(" ", ""));
            feature.put("geometry", geometry);
            feature.put("properties", coords);
            if (!ObjectUtils.isEmpty(coords.getString("Coord")) && !coords.getString("Coord").replace(" ", "").equals("[]]")) {
                coords.remove("Coords");
                coords.remove("Coord");
                features.add(feature);
            }
        }
        jsonObject.put("features", features);
        return jsonObject;
    }

    @Override
    public List<JSONObject> getAllHomestayMerchantCategories() {
        return actMapper.getAllHomestayMerchantCategories();
    }

    @Override
    public JSONObject getImportentTourScence() {
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> list = actMapper.getImportentTourScence();
        jsonObject.put("list", list);
        jsonObject.put("total", list.size());
        return jsonObject;
    }

    @Override
    public JSONObject getScenceVideo(int pageNum, int pageSize) {
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> list = actMapper.getScenceVideo();
        jsonObject.put("list", list);
        jsonObject.put("total", list.size());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getScencePersonCnt() {
        return actMapper.getScencePersonCnt();
    }

    @Override
    public JSONObject getTouristFeedback() {
        int Up_Cnt = actMapper.getTouristFeedbackUpCnt();
        int Deal_Cnt = actMapper.getTouristFeedbackdDealCnt();
        String SatisfactionRate = "0";
        JSONObject Satisfaction = actMapper.getTouristFeedbackSatisfactionRate();
        if (!ObjectUtils.isEmpty(Satisfaction)) {
            Integer satisfactionCnt = Satisfaction.getInteger("满意数量");
            Integer totalCnt = Satisfaction.getInteger("总数量");
            if (totalCnt == 0) {
                SatisfactionRate = "0";
            }
            if (satisfactionCnt == 0) {
                SatisfactionRate = "0";
            } else {
                double v = satisfactionCnt.doubleValue() / totalCnt.doubleValue();
                DecimalFormat df = new DecimalFormat("#.00");
                String str = df.format(v * 100);
                SatisfactionRate = str;
            }
        }

        List<JSONObject> Ring_Data = actMapper.getTouristFeedbackUpList();


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Up_Cnt", Up_Cnt);
        jsonObject.put("Deal_Cnt", Deal_Cnt);
        jsonObject.put("SatisfactionRate", SatisfactionRate);
        jsonObject.put("Ring_Data", Ring_Data);
        return jsonObject;
    }

    @Override
    public List<JSONObject> getBlacklistRanking() {
        //todo 看一下投诉的分类都有啥
        List<JSONObject> blacklistRanking = actMapper.getBlacklistRanking();
        for (int i = 0; i < blacklistRanking.size(); i++) {
            blacklistRanking.get(i).put("rank", i + 1);
        }
        return blacklistRanking;
    }

    @Override
    public JSONObject getComplaintCategory(String townNumber, String villageNumber) {
        List<JSONObject> complaintCategory = actMapper.getComplaintCategory(townNumber, villageNumber);
        List<String> titles = Lists.newArrayList();
        complaintCategory.forEach(category -> {
            String title = category.get("name").toString();
            titles.add(title);
        });
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("xAxis", titles);
        jsonObject.put("data", complaintCategory);
        return jsonObject;
    }

    @Override
    public JSONObject getComplaintGrid(String townNumber, String villageNumber) {
        List<JSONObject> complaintCategory = actMapper.getComplaintGrid(townNumber, villageNumber);
        List<String> titles = Lists.newArrayList();
        List<BigDecimal> data = Lists.newArrayList();
        complaintCategory.forEach(category -> {
            String title = category.get("name").toString();
            titles.add(title);
            data.add(category.getBigDecimal("value"));
        });
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("xAxis", titles);
        jsonObject.put("data", data);
        return jsonObject;
    }

    @Override
    public JSONObject getComplaintEvent(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = actMapper.getComplaintEvent(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getComplaintEventRate(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = actMapper.getComplaintEventRate(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getComplaintEventSuccessRate(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = actMapper.getComplaintEventSuccessRate(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getServiceResourcesTouristFeedback() {
        //todo 定一下 哪些是商户的投诉 那些是服务资源的投诉
        int Up_Cnt = actMapper.getServiceResourcesTouristFeedbackUpCnt();
        int Deal_Cnt = actMapper.getServiceResourcesTouristFeedbackdDealCnt();
        String SatisfactionRate = "0";
        JSONObject Satisfaction = actMapper.getServiceResourcesTouristFeedbackSatisfactionRate();
        if (!ObjectUtils.isEmpty(Satisfaction)) {
            Integer satisfactionCnt = Satisfaction.getInteger("满意数量");
            Integer totalCnt = Satisfaction.getInteger("总数量");
            if (totalCnt == 0) {
                SatisfactionRate = "0";
            }
            if (satisfactionCnt == 0) {
                SatisfactionRate = "0";
            } else {
                double v = satisfactionCnt.doubleValue() / totalCnt.doubleValue();
                DecimalFormat df = new DecimalFormat("#.00");
                String str = df.format(v * 100);
                SatisfactionRate = str;
            }
        }

        List<JSONObject> Ring_Data = actMapper.getServiceResourcesTouristFeedbackUpList();


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Up_Cnt", Up_Cnt);
        jsonObject.put("Deal_Cnt", Deal_Cnt);
        jsonObject.put("SatisfactionRate", SatisfactionRate);
        jsonObject.put("Ring_Data", Ring_Data);
        return jsonObject;
    }

    @Override
    public JSONObject getEmergencyDiversion(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String bluePlateTags = "'紧急避难场所','短期避难场所','长期避难场所'";
        List<JSONObject> complaintEvent = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getServiceResourcesList(String townNumber, String villageNumber, String resourceType, int pageNum, int pageSize) {

        JSONObject jsonObject = new JSONObject();
        List<JSONObject> list;
        if ("公共厕所".equals(resourceType)) {
            String bluePlateTags1 = "'公共厕所'";
            list = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        } else if ("医院".equals(resourceType)) {
            String bluePlateTags1 = "'医院'";
            list = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        } else if ("药店".equals(resourceType)) {
            String bluePlateTags1 = "'药店'";
            list = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        } else if ("避险区".equals(resourceType)) {
            String bluePlateTags1 = "'紧急避难场所','短期避难场所','长期避难场所'";
            list = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
            jsonObject.put("list", list);
        }

        String bluePlateTags1 = "'公共厕所'";
        List<JSONObject> complaintEvent1 = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags1);
        String bluePlateTags2 = "'医院'";
        List<JSONObject> complaintEvent2 = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags2);
        String bluePlateTags3 = "'药店'";
        List<JSONObject> complaintEvent3 = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags3);
        String bluePlateTags4 = "'紧急避难场所','短期避难场所','长期避难场所'";
        List<JSONObject> complaintEvent4 = actMapper.getBluePlateTagsByTagName(townNumber, villageNumber, bluePlateTags4);

        jsonObject.put("toilet", complaintEvent1.size());
        jsonObject.put("hospital", complaintEvent2.size());
        jsonObject.put("drugStore", complaintEvent3.size());
        jsonObject.put("emergencyDiversion", complaintEvent4.size());

        return jsonObject;
    }

    @Override
    public JSONObject getTravelAgency(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = actMapper.getTravelAgency(townNumber, villageNumber);
        // 加入 rank
        for (int i = 0; i < complaintEvent.size(); i++) {
            JSONObject jsonObject1 = complaintEvent.get(i);
            jsonObject1.put("Rank", i + 1);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getTrafficFlowCongestionAnalysis(String dateType) {
        List<String> hourDataList = new ArrayList<>();
        hourDataList.add("08:00");
        hourDataList.add("09:00");
        hourDataList.add("10:00");
        hourDataList.add("11:00");
        hourDataList.add("12:00");
        hourDataList.add("13:00");
        hourDataList.add("14:00");
        hourDataList.add("15:00");
        hourDataList.add("16:00");
        hourDataList.add("17:00");
        hourDataList.add("18:00");

        List<JSONObject> trafficFlowCongestionAnalysis = actMapper.getTrafficFlowCongestionAnalysis(dateType);


        // 根据产生的数据，通过时间进行分组，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
        java.util.Map<String, List<JSONObject>> hourDataMap = trafficFlowCongestionAnalysis.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));
        java.util.Map<String, List<JSONObject>> scenicSpotNameMap = trafficFlowCongestionAnalysis.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Scenic_Spot_Name")));
        // 遍历map，将景点名称、平均速度、拥堵情况进行归类组成不同的集合
        List<String> legend = new ArrayList<>();
        // 遍历map，将时间进行归类组成不同的集合

        List<JSONObject> series = new ArrayList<>();
        for (Map.Entry<String, List<JSONObject>> entry : scenicSpotNameMap.entrySet()) {
            legend.add(entry.getKey());
            JSONObject jsonObject1 = new JSONObject();
            List<String> data1 = new ArrayList<>();
            List<String> data2 = new ArrayList<>();
            for (String xAxi : hourDataList) {
                List<JSONObject> jsonObjects = entry.getValue();
                for (JSONObject jsonObject : jsonObjects) {
                    if (jsonObject.getString("Hour_Data").equals(xAxi)) {
                        data1.add(jsonObject.getString("Average_Speed"));
                        data2.add(jsonObject.getString("Traffic_Jam"));
                    } else {
                        data1.add("0");
                        data2.add("0");
                    }
                }
            }
            jsonObject1.put("Average_Speed", data1);
            jsonObject1.put("Traffic_Jam", data2);
            jsonObject1.put("Name", entry.getKey());
            series.add(jsonObject1);
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("series", series);
        jsonObject.put("xAxis", hourDataList);
        jsonObject.put("legend", legend);

        return jsonObject;
    }

    @Override
    public JSONObject getTrafficFlowPassengerAnalysis(String dateType) {
        List<String> hourDataList = new ArrayList<>();
        hourDataList.add("08:00");
        hourDataList.add("09:00");
        hourDataList.add("10:00");
        hourDataList.add("11:00");
        hourDataList.add("12:00");
        hourDataList.add("13:00");
        hourDataList.add("14:00");
        hourDataList.add("15:00");
        hourDataList.add("16:00");
        hourDataList.add("17:00");
        hourDataList.add("18:00");
        List<JSONObject> trafficFlowPassengerAnalysis = actMapper.getTrafficFlowPassengerAnalysis(dateType);
        java.util.Map<String, List<JSONObject>> hourDataMap = trafficFlowPassengerAnalysis.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Hour_Data")));
        java.util.Map<String, List<JSONObject>> scenicSpotNameMap = trafficFlowPassengerAnalysis.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("Scenic_Spot_Name")));

        List<String> legend = new ArrayList<>();

        List<JSONObject> series = new ArrayList<>();
        for (Map.Entry<String, List<JSONObject>> entry : scenicSpotNameMap.entrySet()) {
            legend.add(entry.getKey());
            JSONObject jsonObject1 = new JSONObject();
            List<String> data1 = new ArrayList<>();
            for (String xAxi : hourDataList) {
                List<JSONObject> jsonObjects = entry.getValue();
                for (JSONObject jsonObject : jsonObjects) {
                    if (jsonObject.getString("Hour_Data").equals(xAxi)) {
                        data1.add(jsonObject.getString("Person_Cnt"));
                    } else {
                        data1.add("0");
                    }
                }
            }
            jsonObject1.put("Person_Cnt", data1);
            jsonObject1.put("Name", entry.getKey());
            series.add(jsonObject1);
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("series", series);
        jsonObject.put("xAxis", hourDataList);
        jsonObject.put("legend", legend);

        return jsonObject;
    }

    @Override
    public JSONObject getInCarCnt() {
        List<JSONObject> inCarList = actMapper.getInCarCnt();
        int inCatTotal = 0;
        for (JSONObject object : inCarList) {
            inCatTotal += object.getInteger("Car_Cnt");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", inCarList);
        jsonObject.put("total", inCatTotal);
        return jsonObject;
    }

    @Override
    public JSONObject getTrafficFlowVideo(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = actMapper.getTrafficFlowVideo();
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getPersonFlowVideo(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> complaintEvent = actMapper.getPersonFlowVideo();
        PageInfo<JSONObject> pageInfo = new PageInfo<>(complaintEvent);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getParkingService() {
        return actMapper.getParkingService();
    }
}
